package com.sc.ktapplication.common.net.okdown;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Response;

public abstract class FileCallBack {

    private String destFileDir;
    private String destFileName;

    public FileCallBack(String destFileDir, String destFileName) {
        this.destFileDir = destFileDir;
        this.destFileName = destFileName;
    }

    public File parseNetworkResponse(Response response, int id) throws Exception {
        return this.saveFile(response, id);
    }

    public File saveFile(Response response, final int id) throws IOException {
        InputStream is = null;
        byte[] buf = new byte[2048];
        FileOutputStream fos = null;

        try {
            is = response.body().byteStream();
            final long total = response.body().contentLength();
            long sum = 0L;
            File dir = new File(this.destFileDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            File file = new File(dir, this.destFileName);
            fos = new FileOutputStream(file);

            int len;
            while((len = is.read(buf)) != -1) {
                sum += (long)len;
                fos.write(buf, 0, len);
                long finalSum = sum;
                inProgress((float) finalSum * 1.0F / (float)total, total, id);
            }

            fos.flush();
            return file;
        } finally {
            try {
                response.body().close();
                if (is != null) {
                    is.close();
                }
            } catch (IOException var23) {
            }

            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException var22) {
            }

        }
    }

    public void inProgress(float progress, long total, int id) {}

    public abstract void onError(Call call, Exception e, int id);

    public abstract void onResponse(File file, int id);

    public boolean validateReponse(Response response, int id) {
        return response.isSuccessful();
    }
}
